"use client"

import { createContext, useContext, useState, useEffect, type ReactNode } from "react"
import {
  login as apiLogin,
  register as apiRegister,
  setToken,
  clearToken,
  getToken,
} from '@/apis/auth';
import { User } from '@/types/user';

interface AuthContextType {
  user: User | null
  login: (username: string, password: string) => Promise<void>
  register: (username:string, email: string, password: string) => Promise<void>
  logout: () => void
  isLoading: boolean
}

const AuthContext = createContext<AuthContextType | undefined>(undefined)

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<User | null>(null)
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    const token = getToken();
    if (token) {
      // You might want to fetch user data from the server here
      // For now, we'll just set a placeholder user
      const storedUser = localStorage.getItem("user");
      if (storedUser) {
        setUser(JSON.parse(storedUser));
      }
    }
    setIsLoading(false)
  }, [])

  const login = async (username: string, password: string):Promise<void> => {
    const response = await apiLogin({ username, password });
    setUser(response.user);
    setToken(response.token);
    localStorage.setItem('user', JSON.stringify(response.user));
  };

  const register = async (username:string,email:string,password:string) => {
    const response = await apiRegister({username,email,password});
    setUser(response.user);
    setToken(response.token);
    localStorage.setItem('user', JSON.stringify(response.user));
  }

  const logout = () => {
    setUser(null)
    clearToken();
    localStorage.removeItem("user");
  }

  return <AuthContext.Provider value={{ user, login, register, logout, isLoading }}>{children}</AuthContext.Provider>
}

export function useAuth() {
  const context = useContext(AuthContext)
  if (context === undefined) {
    throw new Error("useAuth must be used within an AuthProvider")
  }
  return context
}
